package com.wanli.agent.homepage;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseActivity;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.ActivateResultBean;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.MachinesInfoBean;
import com.wanli.agent.bean.ScanActivateBean;
import com.wanli.agent.dialog.CollectCodeDialog;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.DateTimeUtil;
import com.wanli.agent.utils.FastClickUtils;
import com.wanli.agent.utils.NumberFormatUtils;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.AppTitleBar;
import com.wanli.agent.widget.CommonNoTitleDialog;
import com.wanli.agent.widget.ViewLoading;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachinesInfoActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_order_fee)
    TextView tvOrderFee;
    @BindView(R.id.tv_agent_name)
    TextView tvAgentName;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_jihuo_type)
    TextView tvJihuoType;
    @BindView(R.id.tv_jihuo_status)
    TextView tvJihuoStatus;
    @BindView(R.id.tv_jihuo_money)
    TextView tvJihuoMoney;
    @BindView(R.id.tv_return_money)
    TextView tvReturnMoney;
    @BindView(R.id.tv_current_status)
    TextView tvCurrentStatus;
    @BindView(R.id.tv_used_time)
    TextView tvUsedTime;
    @BindView(R.id.ll_jihuo_layout)
    LinearLayout llJihuoLayout;
    @BindView(R.id.tv_push)
    TextView tvPush;
    @BindView(R.id.tv_scan)
    TextView tvScan;
    @BindView(R.id.tv_look_code)
    TextView tvLookCode;
    private String id;
    private IHomePageModel homePageModel = new HomePageModelImpl();
    private MachinesInfoBean.DataBean dataBean;
    private String order_no;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {
            requestReturncashOrderShow();
        }
    };
    private CommonNoTitleDialog.Builder dialogBuild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machines_info);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    public void initView() {
        id = getIntent().getStringExtra("id");
    }

    public void initData() {
        homePageModel.requestDeviceUnifyShow(id, new DataCallBack<MachinesInfoBean>() {
            @Override
            public void onSuccessful(MachinesInfoBean bean) {
                dataBean = bean.getData();
                if ("1".equals(dataBean.getType())) {
                    tvType.setText("扫码盒");
                } else if ("3".equals(dataBean.getType())) {
                    tvType.setText("码牌");
                } else if ("4".equals(dataBean.getType())) {
                    tvType.setText("云音响");
                } else if ("5".equals(dataBean.getType())) {
                    tvType.setText("NFC标签卡");
                } else if ("6".equals(dataBean.getType())) {
                    tvType.setText("码牌音响");
                } else if ("8".equals(dataBean.getType())) {
                    tvType.setText("收款码");
                    tvLookCode.setVisibility(View.VISIBLE);
                }
                tvNumber.setText(dataBean.getPrefix() + dataBean.getNo());
                String money = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(dataBean.getStore_order_fee()) / 100);
                tvOrderFee.setText(money + "元");
                tvAgentName.setText(dataBean.getBind_agent_name());
                tvStoreName.setText(dataBean.getBind_store_name());
                if (dataBean.getIs_need_enable() == 0) {
                    tvJihuoType.setText("免激活");
                    llJihuoLayout.setVisibility(View.GONE);
                } else {
                    tvJihuoType.setText("需要激活");
                    tvJihuoStatus.setText(dataBean.getIs_enable() == 0 ? "未激活" : "已激活");
                    tvJihuoMoney.setText(NumberFormatUtils.formatTwoDecimal(Double.parseDouble(dataBean.getActivate_fee()) / 100) + "元");
                    tvReturnMoney.setText(NumberFormatUtils.formatTwoDecimal(Double.parseDouble(dataBean.getReturncash_fee()) / 100) + "元");
                    llJihuoLayout.setVisibility(View.VISIBLE);
                }
                if (dataBean.getStatus() == 0) {
                    tvCurrentStatus.setText("未使用");
                } else if (dataBean.getStatus() == 1) {
                    tvCurrentStatus.setText("已使用");
                } else if (dataBean.getStatus() == 1) {
                    tvCurrentStatus.setText("已禁用");
                }

                if (!TextUtils.isEmpty(dataBean.getUsed_time()) && !"0".equals(dataBean.getUsed_time())) {
                    tvUsedTime.setText(DateTimeUtil.format7(new Date(Long.parseLong(dataBean.getUsed_time()) * 1000)));
                } else {
                    tvUsedTime.setText("未使用");
                }

                if ("4".equals(dataBean.getType()) || "6".equals(dataBean.getType())) {
                    tvPush.setVisibility(View.VISIBLE);
                } else {
                    tvPush.setVisibility(View.GONE);
                }
                if (dataBean.getIs_need_enable() == 1 && dataBean.getIs_enable() == 0) {
                    tvScan.setVisibility(View.VISIBLE);
                } else {
                    tvScan.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private Dialog progress;

    public void showProgress(String message) {
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);
        try {
            progress.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgress() {
        if (progress == null) {
            return;
        }
        try {
            progress.dismiss();
            progress = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.tv_look_code, R.id.tv_push, R.id.tv_scan})
    public void onViewClicked(View view) {
        if (FastClickUtils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_look_code:
                if (dataBean == null) {
                    return;
                }
                if ("8".equals(dataBean.getType())) {
                    CollectCodeDialog dialog = CollectCodeDialog.newInstance(dataBean.getQrurl(), dataBean.getNo());
                    dialog.show(getSupportFragmentManager(), "dialog");
                }

                break;
            case R.id.tv_push:
                requestTestCloudHorn();
                break;
            case R.id.tv_scan:
                dialogBuild = new CommonNoTitleDialog.Builder(this);
                dialogBuild.setMessage("请扫商家的【微信付款码】或【支付宝付款码】进行激活");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    IntentIntegrator integrator = new IntentIntegrator(mActivity);
                    integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                    integrator.setOrientationLocked(false);
                    integrator.setCaptureActivity(QRActivity.class);
                    integrator.initiateScan();
                });
                dialogBuild.setNegativeButton("取消", v -> {
                    dialogBuild.dismiss();
                });
                dialogBuild.setCancelable(false);
                dialogBuild.show();

                break;
        }
    }

    public void requestTestCloudHorn() {
        if (dataBean == null) {
            return;
        }
        ViewLoading.showProgress(mActivity, "推送中......");
        homePageModel.requestTestCloudHorn(dataBean.getPrefix() + dataBean.getNo(), new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 设备激活
     *
     * @param code
     */
    public void requestDeviceEnable(String code) {
        if (dataBean == null) {
            return;
        }
        if (!NumberFormatUtils.isNumeric(code)) {
            ToastUtil.showShort("请扫描付款码");
            return;
        }
        showProgress("激活中.....");
        homePageModel.requestDeviceEnable(id, dataBean.getNo(), code, dataBean.getPrefix(), new DataCallBack<ScanActivateBean>() {
            @Override
            public void onSuccessful(ScanActivateBean bean) {
                order_no = bean.getData().getOrder_no();
                requestReturncashOrderShow();
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    public void requestReturncashOrderShow() {
        homePageModel.requestReturncashOrderShow(order_no, new DataCallBack<ActivateResultBean>() {
            @Override
            public void onSuccessful(ActivateResultBean bean) {
                if (bean.getData().getPay_status() == 1) {
                    dismissProgress();
                    ToastUtil.showShort("激活成功");
                    initData();
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else {
                    mHandler.postDelayed(mTimeCounterRunnable, 1 * 1000);
                }
                Log.d("--------", "" + order_no);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时任务
        mHandler.removeCallbacks(mTimeCounterRunnable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫描取消", Toast.LENGTH_LONG).show();
            } else {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                String code = scanResult.getContents();
                requestDeviceEnable(code);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
